package com.shinhye.elephantsafe.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.xmlpull.v1.XmlSerializer;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.SystemClock;
import android.util.Xml;

public class SmsBackupUtils {

	/**
	 * A interface to define the progress while SMS backup.
	 * @author ShinHye
	 *
	 */
	public interface SmsProgress {
		/**
		 * Before backup what should be done.
		 * @param total Total of the progressBar or the progressDialog.
		 */
		public void beforeBackup(int total);
		/**
		 * In backup operation what should be done.
		 * @param progress Progress of the progressBar or the progressDialog.
		 */
		public void inBackup(int progress);
	}
	
	/**
	 * Backup for SMS to a specified path.
	 * @param context
	 * @param path - File path with filename.
	 * @throws IOException 
	 * @throws IllegalStateException 
	 * @throws IllegalArgumentException 
	 */
	public static void backupSms(Context context, String path, SmsProgress smsProgress) throws IllegalArgumentException, IllegalStateException, IOException {
		XmlSerializer serializer = Xml.newSerializer();
		File file = new File(path);
		FileOutputStream out = new FileOutputStream(file);
		serializer.setOutput(out, "utf-8");
		serializer.startDocument("utf-8", true);
		serializer.startTag(null, "smss");

		ContentResolver resolver = context.getContentResolver();
		Uri uri = Uri.parse("content://sms");
		Cursor cursor = resolver.query(uri, new String[]{"address","date","type","body"}, null, null, null);
		//设置总进度
		smsProgress.beforeBackup(cursor.getCount());
		
		int progress = 0;
		while(cursor.moveToNext()) {
			serializer.startTag(null, "sms");
			
			serializer.startTag(null, "address");
			serializer.text(cursor.getString(0));
			serializer.endTag(null, "address");
			
			serializer.startTag(null, "date");
			serializer.text(cursor.getString(1));
			serializer.endTag(null, "date");
			
			serializer.startTag(null, "type");
			serializer.text(cursor.getString(2));
			serializer.endTag(null, "type");
			
			serializer.startTag(null, "body");
			serializer.text(cursor.getString(3));
			serializer.endTag(null, "body");
			
			serializer.endTag(null, "sms");
			
			//设置进度
			progress++;
			SystemClock.sleep(100);
			smsProgress.inBackup(progress);
		}
		serializer.endTag(null, "smss");
		serializer.endDocument();
		
	}
}
